package com.cmccgz.baselibrary.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.cmccgz.baselibrary.R;
import com.cmccgz.baselibrary.utils.SystemBarTintManager;
import com.cmccgz.baselibrary.utils.ToastUtils;
import com.orhanobut.logger.Logger;

/**
 * @author: Huang
 * @Descripion:
 * @date 2017/5/23 15:05
 */

public abstract class BaseActivity extends AppCompatActivity {

    protected Context mContext;
    private PermissionUtils.PermissionAskCallback baseCallback;
    protected ProgressDialog progressDialog;
    protected AlertDialog alertDialog;
    protected FragmentManager fragmentManager;
    protected Handler handler = new Handler();
    private String preTag;
    protected String currentTag;
    protected boolean isSaveInstance;
    private Bundle savedInstanceState;
    protected boolean isShowTimeLog =false;
    protected AlertDialog tipsDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showTimeLog("onCreate");
        isSaveInstance = savedInstanceState != null;
        this.savedInstanceState = savedInstanceState;
        if (savedInstanceState != null) {
            currentTag = savedInstanceState.getString("currentTag");
            preTag = savedInstanceState.getString("preTag");
        }
        mContext = this;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView();
        initSystemBar();
        beforePermission();
        fragmentManager = getSupportFragmentManager();
        baseCallback = new PermissionUtils.PermissionAskCallback() {
            @Override
            public void hasPermissionDoNext() {
                initView();
                initFragment();
            }
        };
        initBaseView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        showTimeLog("onResume");
    }

    @Override
    protected void onStart() {
        super.onStart();
        showTimeLog("onStart");
    }

    @Override
    protected void onDestroy() {
        ToastUtils.clean();
        showTimeLog("onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("currentTag", currentTag);
        outState.putString("preTag", preTag);
        super.onSaveInstanceState(outState);
        showTimeLog("onSaveInstanceState");
    }

    private void initBaseView() {
        PermissionUtils.askPermission(this, PermissionUtils.REQUEST_CODE_ASK_BASE_PERMISSIONS, baseCallback, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE);
    }

    @LayoutRes
    protected abstract int setLayoutId();

    protected abstract void initView();

    protected abstract void initFragment();

    protected abstract void beforePermission();

    protected abstract int setSystemBarColorId();

    protected void showFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentTransaction.setCustomAnimations(R.anim.anim_enter, R.anim.anim_exit, R.anim.anim_pop_enter, R.anim.anim_pop_exit);
        }
        String simpleName = fragment.getClass().getSimpleName();
        Fragment interFragment = fragmentManager.findFragmentByTag(simpleName);
        if (interFragment!=null) {
            fragmentTransaction.remove(interFragment).commit();
        }
        preTag = currentTag;
        currentTag = simpleName;
        fragmentTransaction.replace(R.id.contentFrame, fragment, simpleName).addToBackStack(simpleName).commit();
    }

    protected void showFragment(Fragment fragment, boolean isAnima, boolean isPopAnima) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(isAnima ? R.anim.anim_enter : 0,
                isAnima ? R.anim.anim_exit : 0,
                isPopAnima ? R.anim.anim_pop_enter : 0,
                isPopAnima ? R.anim.anim_pop_exit : 0);
        String simpleName = fragment.getClass().getSimpleName();
        preTag = currentTag;
        currentTag = simpleName;
        fragmentTransaction.replace(R.id.contentFrame, fragment, simpleName).addToBackStack(simpleName).commit();
    }

    protected void fragmentBack() {
        if (fragmentManager.getBackStackEntryCount() > 1) {
            fragmentManager.popBackStack();
            currentTag = preTag;
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        fragmentBack();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.REQUEST_CODE_ASK_BASE_PERMISSIONS) {
            PermissionUtils.handlePermissionRequest(permissions, grantResults, this, baseCallback, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
        }
    }

    protected void initSystemBar() {
        Window window = getWindow();

        int systemBarColor = setSystemBarColorId();
        if (systemBarColor == 0) {
            systemBarColor = R.color.toolBarColor;
        }
        //4.4.2设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        //5.0设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(mContext, systemBarColor));
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        // 使用颜色资源
        tintManager.setStatusBarTintResource(systemBarColor);

    }

    /**
     * 设置contentView
     */
    private void setContentView() {
        View contentView = View.inflate(mContext, setLayoutId() == 0 ? R.layout.activity_base : setLayoutId(), null);
        //设置clipToPadding与fitsSystemWindows
        try {
            if (contentView instanceof ViewGroup) {
                ((ViewGroup) contentView).setClipToPadding(true);
                contentView.setFitsSystemWindows(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setContentView(contentView);
    }

    @TargetApi(19)
    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 设置点击间隔
     *
     * @param v
     * @param spanMis
     */
    protected void setClickSpan(final View v, long spanMis) {
        v.setClickable(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                v.setClickable(true);
            }
        }, spanMis);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
    }

    public void startActivity(Intent intent, boolean showAnima) {
        super.startActivity(intent);
        if (showAnima) {
            overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
    }

    public void startActivityForResult(Intent intent, int requestCode, boolean showAnima) {
        super.startActivityForResult(intent, requestCode);
        if (showAnima) {
            overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_pop_enter, R.anim.anim_pop_exit);
    }

    public void finish(boolean showAnim) {
        if (showAnim) {
            finish();
        } else {
            super.finish();
        }
    }

    /**
     * 隐藏软键盘
     *
     * @param v
     */
    protected void hideSoftKeyboard(View v) {
        try {
            InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制隐藏软键盘
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        showTimeLog("onPause");
        hideSoftKeyboard(getWindow().getDecorView());
    }

    @Override
    protected void onStop() {
        super.onStop();
        showTimeLog("onStop");
    }

    protected void showToast(String message) {
        ToastUtils.show(mContext, message);
    }

    protected void showToast(@StringRes int stringId) {
        ToastUtils.show(mContext, stringId);
    }

    protected void showLoadingDialog(String message) {
        try {
            progressDialog = ProgressDialog.show(mContext, "", message, false, true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void showLoadingDialog(String message, DialogInterface.OnCancelListener cancelListener) {
        try {
            progressDialog = ProgressDialog.show(mContext, "", message, false, true, cancelListener);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void dismissLoadingDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }

    protected void showConfirmDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener, String cancleText, DialogInterface.OnClickListener onCancleClickListener) {
        showConfirmDialog(title,message,okText,onOkClickListener,cancleText,onCancleClickListener,true);
    }
    protected void showConfirmDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener, String cancleText, DialogInterface.OnClickListener onCancleClickListener,boolean isCancelable) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(isCancelable).setTitle(title).setMessage(message).setPositiveButton(okText, onOkClickListener).setNegativeButton(cancleText, onCancleClickListener);
            alertDialog= builder.create();
            alertDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }
    protected Bundle getSavedInstanceState() {
        return savedInstanceState;
    }

    private void showTimeLog(String msg) {
        if (isShowTimeLog) {
            Logger.i(getClass().getSimpleName() + "---=" + msg);
        }
    }

    protected void showTipsDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener) {
     /*   try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title).setMessage(message).setPositiveButton(okText, onOkClickListener);
            tipsDialog = builder.create();
            tipsDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }*/
        showTipsDialog(title,message,okText,onOkClickListener,null);
    }

    protected void showTipsDialog(String title, String message, String okText, DialogInterface.OnClickListener onOkClickListener,DialogInterface.OnDismissListener onDismissListener) {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(title).setMessage(message).setPositiveButton(okText, onOkClickListener).setOnDismissListener(onDismissListener);
            tipsDialog = builder.create();
            tipsDialog.show();
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }
}
